package org.jeecg.modules.category.rule;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.jeecg.common.handler.IFillRuleHandler;
import org.jeecg.common.util.SpringContextUtils;
import org.jeecg.common.util.YouBianCodeUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.category.entity.AoCategory;
import org.jeecg.modules.category.mapper.AoCategoryMapper;

import java.util.List;

/**
 * 题库分类编码生成规则
 *
 * @author thankgod7
 */
@SuppressWarnings("unused")
public class AoCategoryCodeRule implements IFillRuleHandler {

    public static final String ROOT_PID_VALUE = "0";

    /**
     * 分成三种情况
     * 1.数据库无数据 调用YouBianCodeUtil.getNextYouBianCode(null);
     * 2.添加子节点，无兄弟元素 YouBianCodeUtil.getSubYouBianCode(parentCode,null);
     * 3.添加子节点有兄弟元素 YouBianCodeUtil.getNextYouBianCode(lastCode);
     */
    @Override
    public Object execute(JSONObject params, JSONObject formData) {

        String categoryPid = ROOT_PID_VALUE;
        String categoryCode;

        if (formData != null && formData.size() > 0) {
            Object obj = formData.get("pid");
            if (oConvertUtils.isNotEmpty(obj)) {
                categoryPid = obj.toString();
            }
        } else {
            if (params != null) {
                Object obj = params.get("pid");
                if (oConvertUtils.isNotEmpty(obj)) {
                    categoryPid = obj.toString();
                }
            }
        }

        //找同类 确定上一个最大的code值
        LambdaQueryWrapper<AoCategory> query = new LambdaQueryWrapper<AoCategory>().eq(AoCategory::getPid, categoryPid).isNotNull(AoCategory::getCode).orderByDesc(AoCategory::getCode);
        AoCategoryMapper baseMapper = (AoCategoryMapper) SpringContextUtils.getBean("aoCategoryMapper");
        List<AoCategory> list = baseMapper.selectList(query);
        if (list == null || list.size() == 0) {
            if (ROOT_PID_VALUE.equals(categoryPid)) {
                //情况1
                categoryCode = YouBianCodeUtil.getNextYouBianCode(null);
            } else {
                //情况2
                AoCategory parent = baseMapper.selectById(categoryPid);
                categoryCode = YouBianCodeUtil.getSubYouBianCode(parent.getCode(), null);
            }
        } else {
            //情况3
            categoryCode = YouBianCodeUtil.getNextYouBianCode(list.get(0).getCode());
        }
        return categoryCode;
    }
}
